package com.zhouxiaoge.mybatis.jdbc;

import java.sql.*;

/**
 * @author 周小哥
 * @Create 2020年03月23日 10:27
 * @email gqzmy@163.com
 */

public class JDBCMain {

    public static void main(String[] args) {

        String MYSQL_URL = "jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf-8";
        String MYSQL_NAME = "root";
        String MYSQL_PASSWORD = "1234";

        Connection connection = null;
        PreparedStatement preparedStatement = null;
        ResultSet resultSet = null;

        try {
            // 1、加载数据库驱动
            Class.forName("com.mysql.cj.jdbc.Driver");
            // 2、通过驱动管理类获取数据库链接
            connection = DriverManager.getConnection(MYSQL_URL, MYSQL_NAME, MYSQL_PASSWORD);

            // 3、定义sql
            String sql = "select * from user ";

            // 4、获取预处理statement
            preparedStatement = connection.prepareStatement(sql);

            // 5、设置参数，第一个参数为sql语句中参数的序号(从1开始），第二个参数为设置的参数值
//            preparedStatement.setString(1, "tom");

            // 6、执行sql，查出结果集
            resultSet = preparedStatement.executeQuery();

            // 7、遍历结果集
            while (resultSet.next()) {
                int id = resultSet.getInt("id");
                String user_name = resultSet.getString("user_name");
                System.out.println("id : " + id);
                System.out.println("username : " + user_name);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }finally {
            if (resultSet != null) {
                try {
                    resultSet.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (preparedStatement != null) {
                try {
                    preparedStatement.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if (connection != null) {
                try {
                    connection.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }

            }
        }

    }
}
